//
//  OAuthViewController.swift
//  ZYBWeibo
//
//  Created by xthink4 on 16/2/29.
//  Copyright © 2016年 zyb. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController,UIWebViewDelegate {
    let WB_CLIENT_ID="4048103256"
    let WB_App_Secret="91a2ae479a6398806170152d57280c0a"
    let WB_REDIRECT_URI="http://news.baidu.com"
    @IBOutlet var loginWebView: UIWebView!
    ///关闭当前视图
    @IBAction func closeView(sender: UIBarButtonItem) {
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loginWebView.delegate=self
        loadAuthWebView()

        // Do any additional setup after loading the view.
    }

    ///加载授权页面
    private func loadAuthWebView(){
        let urlString="https://api.weibo.com/oauth2/authorize?client_id="+WB_CLIENT_ID+"&redirect_uri="+WB_REDIRECT_URI+""
        let url=NSURL(string: urlString)!
        loginWebView.loadRequest(NSURLRequest(URL: url))
    }
    
    /**
     1>https://api.weibo.com/oauth2/authorize?client_id=4048103256&redirect_uri=http://news.baidu.com 请求授权页面
     2>http://news.baidu.com/?code=2a7f5aa4f0d146e14ea0ea17b632f39c 授权成功
     3>http://news.baidu.com/?error_uri=%  取消授权
     4>https://api.weibo.com 继续加载
     **/
    ///webView代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request:
        
        NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.URL)
            let urlString=request.URL!.absoluteString
            //如果是官方地址，继续加载
            if urlString.hasPrefix("https://api.weibo.com/"){
                return true
            }
            //如果不是回调地址不做处理
            if !urlString.hasPrefix(WB_REDIRECT_URI){
                return false
            }
            let codeStr="code="
            let query=request.URL!.query!
            if query.hasPrefix(codeStr){//获取请求码
                let code=(query as NSString).substringFromIndex(codeStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
                get_Accsee_Token(code)
               
            }else{//用户拒绝授权
                print("拒绝授权")
                dismissViewControllerAnimated(true, completion: nil)
            }
            
        
        return true
    }
    
      ///获取token值
    private func get_Accsee_Token(code:String){
        
        let paraDict:Dictionary=["client_id":WB_CLIENT_ID,
            "client_secret":WB_App_Secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WB_REDIRECT_URI
            ]
        loadUserAccess_token(paraDict)
        
    }
    ///获取access_token
    private func loadUserAccess_token(paraDict:[String:String]){
        
        let urlString="https://api.weibo.com/oauth2/access_token"
        
        NetWorkTools.requestJSON(.POST, urlString: urlString) { (JSON) -> Void in
            let token_dict=JSON
            let access_token=token_dict?.objectForKey("access_token")
            let expires_in=token_dict?.objectForKey("expires_in")
            let remind_in=token_dict?.objectForKey("remind_in")
            let uid=token_dict?.objectForKey("uid")
            //将用access_Token存储在NSUserDefaults
            let userToken=NSUserDefaults.standardUserDefaults()
            userToken.setObject(access_token, forKey: "access_token")
            userToken.setObject(expires_in, forKey: "expires_in")
            userToken.setObject(remind_in, forKey: "remind_in")
            userToken.setObject(uid, forKey: "uid")
            print("==token==\(access_token)")
            self.getUserInfo()
        }
       
    }
    ///获取登陆用户信息
    private func getUserInfo(){
        
        let urlString="https://api.weibo.com/2/users/show.json"
        let access_token=NSUserDefaults.standardUserDefaults().objectForKey("access_token") as! String
        let uid=NSUserDefaults.standardUserDefaults().objectForKey("uid")as!String
        let params:Dictionary<String,String>=["access_token":access_token,"uid":uid]
        NetWorkTools.requestJSON(.GET, urlString: urlString, parameters: params) { (JSON) -> Void in
            let dict:Dictionary<String,AnyObject>=JSON as! Dictionary
            let userInfo:UserModel=UserModel()
            userInfo.setValuesForKeysWithDictionary(dict)
            let defaults=NSUserDefaults.standardUserDefaults()
            defaults.setObject(userInfo.avatar_hd, forKey: "avatar_hd")
            defaults.setObject(userInfo.name, forKey:"userName")
            defaults.setObject(userInfo.id, forKey: "id")
            
            NSNotificationCenter.defaultCenter().postNotificationName(YBSwithRootViewControllerNSNotification, object: "Wellcome")
            self.dismissViewControllerAnimated(true, completion: nil)
        }
       
    }

    

}
